package dian.qing.li.demo.security.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.pactera.redis.utils.RedisUtils;
import dian.qing.li.demo.security.constants.Constants;
import dian.qing.li.demo.security.constants.RedisKey;
import dian.qing.li.demo.security.dto.AuthRequestDto;
import dian.qing.li.demo.security.mapper.AuthRequestMapper;
import dian.qing.li.demo.security.service.AuthRequestService;
import dian.qing.li.demo.security.utils.Assert;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限-请求资源表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-07-01
 */
@Service
public class AuthRequestServiceImpl extends ServiceImpl<AuthRequestMapper, AuthRequestDto> implements AuthRequestService {

    private static final AntPathMatcher MATCHER = new AntPathMatcher();

    @Override
    public List<String> getAuthorities(String method, String requestURI) {
        Assert.isNotBlank(method, "[method]不能为空");
        Assert.isNotBlank(requestURI, "[requestURI]不能为空");
        String redisKey = RedisUtils.redisKey(RedisKey.AUTH_REQUEST_LIST);
        List<AuthRequestDto> list = RedisUtils.get(redisKey, List.class);
        if (list == null) {
            list = this.list();
            RedisUtils.put(redisKey, list);
        }
        Set<String> authCodeSet = list.stream().filter(a -> StringUtils.equalsIgnoreCase(method, a.getReqMethod()) && MATCHER.match(requestURI, a.getReqValue())).map(AuthRequestDto::getAuthCode).collect(Collectors.toSet());
        if (CollectionUtils.isEmpty(authCodeSet)) {
            return Lists.newArrayList(Constants.ANONYMOUS_USER);
        }
        return Lists.newArrayList(authCodeSet);
    }
}
